/**
 * 第三方应用登录
 */
var thirdapp = thirdapp||{};

thirdapp.timer = thirdapp.timer||[];
//登录主函数
function thirdAppLogin(appName,appCode,login_url,login_param,checksession_url,heartBeat_gap){
	if(!login_param||!login_url){alert("缺少登录"+appName+"的参数，单点登录失败!");return false;}
	heartBeat_gap = heartBeat_gap || 1000*60*30;//10min
	thirdapp.appName = {
			appCode:appCode,
			login_success:false,
			checksession_url:checksession_url,
			heartBeat_gap:heartBeat_gap
			};
	thirdApplogin(appName,login_url,login_param);
}
//-----------------------
//jsonp登录
function thirdApplogin(appName,login_url,login_param){
     $.jsonp({
    	 url:login_url,
    	 data:login_param,
    	 async:false,
    	 success:function(data,s,xrh){
    	 	if(1 == data.status){
    	 		with(thirdapp.appName){
	    	 		login_success = true;
	    	 		//登录成功后创建定时刷新任务，防止session过期
	    	 		createSessionJob(appCode,checksession_url,heartBeat_gap);
	    	 		log("thirdapp["+appName+"]login  success! [para:"+login_param+"]");
    	 		}
    	 	}else{
    	 		log("thirdapp["+appName+"]login fail ,para:["+login_param+"] [status:"+data.status+",msg:"+data.msg);
    	 	}
         },
         error:function(a,b,c){
        	 alert(appName+"单点登录失败"+[a.data,b,c]);
        	 log("thirdapp["+appName+"]login  error,para:["+login_param+"] ,ajax error:"+[a,b,c]);
         }
     });
 } ;

 //定时请求某个界面，以防止seesion过期
 function createSessionJob(appCode,checksession_url,heartBeat_gap){
	 var timer_id  =  setInterval('job_request("'+appCode+'","'+checksession_url+'")',heartBeat_gap);
	 thirdapp.timer.push(timer_id);
 }
 function job_request(appCode,checksession_url){
	if(!$('#job'+appCode)[0]){
		$(window.document.body).append($('<iframe id=job'+appCode+' style="display: none;"></iframe>'));
	}
	$('#job'+appCode)[0].src=checksession_url;
 };
//界面退出的时候删除定时任务
 window.onunload = function(){
 	for(var timer_id in thirdapp.timer){
 		 window.clearInterval(timer_id);//
 	}
 }
 //记录每次登录日志，方便出错时的问题查找
 function log(msg){
	 $.jsonPost({
		    url:_ctx+"/pub/thirdapp_log.do",
		    data:"msg="+msg,
		    async:true,
			jsonStatusSuccessCall:function(){},
		    jsonStatusFailCall:function(){},
		    error:function(){},
		    complete:function(){}
	});
 };
 